package com.baselibrary.utils

import android.app.Activity
import android.app.AlertDialog
import android.util.TypedValue
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.widget.*
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.baselibrary.Constants
import com.baselibrary.R
import com.baselibrary.adapter.*
import com.baselibrary.bean.BottomDialogBean
import com.baselibrary.bean.FriendListBean
import com.baselibrary.extension.*
import com.baselibrary.manager.SensorsDataManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.router.ShareHelp
import com.baselibrary.view.MyCircleProgress
import com.baselibrary.view.RoundCornerImageView
import com.baselibrary.view.SpacesVerticalDec
import com.baselibrary.view.WheelView

object PopUtils {
    interface ICallBack {
        fun clickOk()
        fun clickCancel()
    }

    interface ICallBackOne {
        fun clickOk()
    }

    interface IitemCallBack {
        fun onItemClick(pos: Int)
    }

    interface IitemCallBackStr {
        fun onOkClick(startTimeStr: String, endTimeStr: String)
    }

    /**
     * @author: merbng
     * @time: 2021/9/28 20:50
     * @description: isSingleBtn：true 只显示确认按钮
     */
    @JvmStatic
    fun showOkCancelDialog(act: Activity, content: String, callback: ICallBack, isSingleBtn: Boolean = false, rightStr: String = "确认", leftStr: String = "取消", isCancelable: Boolean = true): AlertDialog {
        val v = act.layoutInflater.inflate(R.layout.dialog_order_confirm_cancel, null)
        val dialog = showDialog(act, v, Gravity.CENTER, isCancelable)
        val tvContent = v.findViewById<TextView>(R.id.tv_content)
        tvContent.text = "${content}"
        if (content.contains("\n")) {
            //缩小字体 16sp
            tvContent.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f)
        } else {
            //大字体 20sp
            tvContent.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f)
        }
        val tvRight = v.findViewById<TextView>(R.id.tv_ok)
        tvRight.text = "${rightStr}"
        tvRight.setOnClickListener {
            //确定
            callback.clickOk()
            dialog.dismiss()
        }
        //单个按钮
        val tvLeft = v.findViewById<TextView>(R.id.tv_cancel)
        tvLeft.visibility = if (isSingleBtn) View.GONE else View.VISIBLE
        tvLeft.text = "${leftStr}"
        tvLeft.setOnClickListener {
            callback.clickCancel()
            dialog.dismiss()
        }
        return dialog
    }

    @JvmStatic fun showPermissionDialog(act: Activity, callback: ICallBack): AlertDialog {
        val v = act.layoutInflater.inflate(R.layout.dialog_request_permission, null)
        val dialog = showDialog(act, v, Gravity.CENTER, true)
        val tvRight = v.findViewById<TextView>(R.id.tv_ok)
        tvRight.setOnClickListener {
            //确定
            callback.clickOk()
            dialog.dismiss()
        }
        //单个按钮
        val tvLeft = v.findViewById<TextView>(R.id.tv_cancel)
        tvLeft.setOnClickListener {
            callback.clickCancel()
            dialog.dismiss()
        }
        return dialog
    }

    @JvmStatic
    fun showOkCancelDialogNew(act: Activity, content: String, callback: ICallBack, isSingleBtn: Boolean = false, rightStr: String = "确认", leftStr: String = "取消", isCancelable: Boolean = true): AlertDialog {
        val v = act.layoutInflater.inflate(R.layout.dialog_order_confirm_cancel_new, null)
        val dialog = showDialog(act, v, Gravity.CENTER, isCancelable)
        val tvContent = v.findViewById<TextView>(R.id.tv_content)
        tvContent.text = "${content}"
        tvContent.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18f)
        val tvRight = v.findViewById<TextView>(R.id.tv_ok)
        tvRight.text = "${rightStr}"
        tvRight.setOnClickListener {
            //确定
            callback.clickOk()
            dialog.dismiss()
        }
        //单个按钮
        val tvLeft = v.findViewById<TextView>(R.id.tv_cancel)
        tvLeft.visibility = if (isSingleBtn) View.GONE else View.VISIBLE
        tvLeft.text = "${leftStr}"
        tvLeft.setOnClickListener {
            callback.clickCancel()
            dialog.dismiss()
        }
        return dialog
    }

    /**
     * @author: merbng
     * @time: 2021/9/28 20:50
     */
    @JvmStatic
    fun showDialog(act: Activity, title: String, content: String, callback: ICallBack, rightStr: String = "确认", leftStr: String = "取消") {
        val v = act.layoutInflater.inflate(R.layout.dialog_uplock_pul, null)
        val dialog = showDialog(act, v)
        val tvTitle = v.findViewById<TextView>(R.id.tv_title)
        val tvContent = v.findViewById<TextView>(R.id.tv_content)
        val tvRight = v.findViewById<TextView>(R.id.tv_ok)
        val tvCancel = v.findViewById<TextView>(R.id.tv_cancel)
        tvTitle.paint.isFakeBoldText = true
        tvTitle.text = title
        tvContent.text = content
        tvRight.text = rightStr
        tvCancel.text = leftStr

        tvRight.setOnClickListener {
            //确定
            callback.clickOk()
            dialog.dismiss()
        }

        tvCancel.setOnClickListener {
            callback.clickCancel()
            dialog.dismiss()
        }
    }

    fun showDialog(act: Activity, view: View, gravity: Int = Gravity.CENTER, isCancelable: Boolean = true): AlertDialog {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(isCancelable)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        window.setContentView(view)
        window.setGravity(gravity)
        return dialog
    }

    //底部弹窗菜单
    fun showBottomDialog(act: Activity, title: String? = "", dataList: MutableList<BottomDialogBean>, callBack: IitemCallBack, highlightCancel: Boolean = true): AlertDialog {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.MATCH_PARENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.popup_im_more, null)

        view.findViewById<TextView>(R.id.tv_cancel).setTextColor(ContextCompat.getColor(act, if (highlightCancel) R.color.color_D53 else R.color.color_333333))

        val rv = view.findViewById<RecyclerView>(R.id.rv_pop)
        view.findViewById<RelativeLayout>(R.id.rl_root).setOnClickListener { dialog.dismiss() }
        view.findViewById<TextView>(R.id.tv_cancel).setOnClickListener { dialog.dismiss() }
        view.findViewById<TextView>(R.id.tv_title).text = "$title"
        view.findViewById<TextView>(R.id.tv_title).visibility = if (title.checkNotNull()) View.VISIBLE else View.GONE
        view.findViewById<View>(R.id.view_line).visibility = if (title.checkNotNull()) View.VISIBLE else View.GONE
        val adapter = ItemListAdapter()
        rv.adapter = adapter
        rv.addItemDecoration(SpacesVerticalDec(1))
        adapter.setNewData(dataList)
        adapter.setOnItemClickListener { adapter, view, position ->
            callBack.onItemClick(position)
            dialog.dismiss()
        }
        window.setContentView(view)
        window.setGravity(Gravity.BOTTOM)
        return dialog
    }

    fun showCancelFollow(act: Activity, callback: ICallBack) {
        val v = act.layoutInflater.inflate(R.layout.pop_follow_cancel, null)
        val dialog = showDialog(act, v)
        val tvRight = v.findViewById<TextView>(R.id.tv_ok)
        tvRight.setOnClickListener {
            //确定
            callback.clickOk()
            dialog.dismiss()
        }
        //单个按钮
        val tvLeft = v.findViewById<TextView>(R.id.tv_cancel)
        tvLeft.setOnClickListener {
            dialog.dismiss()
        }
    }

    //底部选择的人数
    private val bottomSelectAdapter by lazy { BottomSelectAdapter() }

    interface IBottomShareCallBack {
        fun clickOk(content: String)
        fun clickCancel()
    }

    //私信给好友动态弹窗
    fun showBottomShareDialog(act: Activity, type: Int, coverUrl: String?, dateList: MutableSet<FriendListBean>, callback: IBottomShareCallBack): AlertDialog {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp

        val view = act.layoutInflater.inflate(R.layout.popup_share_bottom, null)
        val rvShareSelect = view.findViewById<RecyclerView>(R.id.rv_share_select)

        //动态封面
        view.findViewById<RoundCornerImageView>(R.id.riv_cover).load(act, coverUrl.checkValue())
        // 动态类型  1：图片 2：视频 3直播、4文章、5 百科  6 讲坛的视频详情 使用常量com.baselibrary.Constants
        view.findViewById<ImageView>(R.id.img_is_video).visibility = if (type == Constants.DYNAMIC_TYPE_VIDEO) View.VISIBLE else View.GONE
        val etInput = view.findViewById<EditText>(R.id.et_input)
        rvShareSelect.layoutManager = LinearLayoutManager(act, LinearLayoutManager.HORIZONTAL, false)
        rvShareSelect.adapter = bottomSelectAdapter
        bottomSelectAdapter.setNewData(dateList.toMutableList())
        etInput.addTextChangedListenerClosure(afterTextChanged = {
            if (it.toString().length == Constants.LIMIT_SHARE_WORD_NUM) {
                "消息字数限制1000字以下".toast()
            }
        })
        view.findViewById<TextView>(R.id.tv_send).setOnClickListener {
            callback.clickOk(etInput.text.toString().checkValue())
        }
        dialog.setOnDismissListener {
            callback.clickCancel()
        }
        window.setContentView(view)
        window.setGravity(Gravity.BOTTOM)
        return dialog
    }

    private val shareHelp = ActivityRouter.getARouterInterface<ShareHelp>(ActivityRouter.ACTIVITY.SHARE_HELP)

    //切换经营者&社区模式  isSwitchManagerMode:true:切换经营者模式 false：社区模式
    @JvmStatic
    fun showSwitchManagerMode(act: Activity, isSwitchManagerMode: Boolean, callback: ICallBackOne) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.popup_switch_manager_mode, null)
        val imgCenter = view.findViewById<ImageView>(R.id.img_center)
        val tvModeTitle = view.findViewById<TextView>(R.id.tv_mode_title)
        val tvDesc = view.findViewById<TextView>(R.id.tv_desc)
        view.findViewById<RelativeLayout>(R.id.rl_root).setOnClickListener { dialog.dismiss() }
        view.findViewById<RelativeLayout>(R.id.rl_bottom).setOnClickListener { }
        imgCenter.load(view.context, if (isSwitchManagerMode) R.drawable.ic_switch_mode_center_2 else R.drawable.ic_switch_mode_center_1)
        tvModeTitle.text = if (isSwitchManagerMode) "经营者模式" else "社区模式"
        tvDesc.text = if (isSwitchManagerMode) "维护线上酒窖、统计经营数据、查询企业政策" else "发布日常动态、好友互动聊天、学习酱酒文化"
        view.findViewById<ImageView>(R.id.img_close).setOnClickListener { dialog.dismiss() }
        view.findViewById<TextView>(R.id.tv_enter).setOnClickListener {
            callback.clickOk()
            dialog.dismiss()
            SpUtils.getInstance().saveLaunchWineryManage(isSwitchManagerMode)
            if (isSwitchManagerMode) ARouterUtils.jump(ActivityRouter.WINE_CELLAR.WINCE_CELLAR_MANAGER_CENTER) else ARouterUtils.jump(ActivityRouter.ACTIVITY.MAIN_PAGE);
            HKToastUtils.showToast(if (isSwitchManagerMode) "已进入经营者模式" else "已进入社区模式")
            SensorsDataManager.instance.modeSwitching(if (isSwitchManagerMode) "进入经营者模式" else "进入社区模式")
            shareHelp.chatImConnectOrDisConnect(!isSwitchManagerMode)
            if (!isSwitchManagerMode) {//启动--经营者中心--个人中心，返回后 需要关闭经营者中心
                act.finish()
            }
        }
        window.setContentView(view)
        window.setGravity(Gravity.BOTTOM)
    }

    //00:00--23:59 时间段选择弹窗
    fun showHourMinuteTimeSectionSelectDialog(act: Activity, callback: IitemCallBackStr) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        window.setContentView(R.layout.pop_hour_minute_time_section_select)
        window.setGravity(Gravity.BOTTOM)
        val wheelHour1 = window.findViewById<WheelView>(R.id.wv_hour_1)
        val wheelMinute1 = window.findViewById<WheelView>(R.id.wv_minute_1)
        val wheelHour2 = window.findViewById<WheelView>(R.id.wv_hour_2)
        val wheelMinute2 = window.findViewById<WheelView>(R.id.wv_minute_2)

        val hourList = mutableListOf<String>()
        val minuteList = mutableListOf<String>()
        var houtStr1 = ""
        var minuteStr1 = ""
        var houtStr2 = ""
        var minuteStr2 = ""

        for (i in 0..23) {
            hourList.add(if (i < 10) "0${i}" else "${i}")
        }
        for (i in 0..59) {
            minuteList.add(if (i < 10) "0${i}" else "${i}")
        }
        wheelHour1.setOffset(2);// 对话框中当前项上面和下面的项数
        wheelHour1.setItems(hourList);// 设置数据源
        wheelHour1.setSeletion(0);// 默认选中第三项
        wheelHour1.setOnWheelViewListener(object : WheelView.OnWheelViewListener() {
            override fun onSelected(selectedIndex: Int, item: String?) {
                super.onSelected(selectedIndex, item)
                houtStr1 = item.checkValue()
            }
        })
        wheelMinute1.setOffset(2);// 对话框中当前项上面和下面的项数
        wheelMinute1.setItems(minuteList);// 设置数据源
        wheelMinute1.setSeletion(0);// 默认选中第三项
        wheelMinute1.setOnWheelViewListener(object : WheelView.OnWheelViewListener() {
            override fun onSelected(selectedIndex: Int, item: String?) {
                super.onSelected(selectedIndex, item)
                minuteStr1 = item.checkValue()
            }
        })
        wheelHour2.setOffset(2);// 对话框中当前项上面和下面的项数
        wheelHour2.setItems(hourList);// 设置数据源
        wheelHour2.setSeletion(0);// 默认选中第三项
        wheelHour2.setOnWheelViewListener(object : WheelView.OnWheelViewListener() {
            override fun onSelected(selectedIndex: Int, item: String?) {
                super.onSelected(selectedIndex, item)
                houtStr2 = item.checkValue()
            }
        })
        wheelMinute2.setOffset(2);// 对话框中当前项上面和下面的项数
        wheelMinute2.setItems(minuteList);// 设置数据源
        wheelMinute2.setSeletion(0);// 默认选中第三项
        wheelMinute2.setOnWheelViewListener(object : WheelView.OnWheelViewListener() {
            override fun onSelected(selectedIndex: Int, item: String?) {
                super.onSelected(selectedIndex, item)
                minuteStr2 = item.checkValue()
            }
        })
        window.findViewById<TextView>(R.id.tv_ok).setOnClickListener {
            callback.onOkClick("${houtStr1}:${minuteStr1}", "${houtStr2}:${minuteStr2}")
            dialog.dismiss()
        }
    }


    interface ICallback4Progress {
        fun progressCallback(progressView: MyCircleProgress, tvProgress: TextView)
    }

    //发布 线上酒币编辑、发布下酒菜（编辑）、发布评论（编辑）、发布酒窖动态在发布页面点击“发布”时增加loading
    fun uploadLoadingDialog(act: Activity, callback: ICallback4Progress): AlertDialog {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        window.setContentView(R.layout.dialog_uploading)
        window.setGravity(Gravity.CENTER)
        val progressView = window.findViewById<MyCircleProgress>(R.id.pro)
        val tvTip = window.findViewById<TextView>(R.id.tv_bottom_tip)
        callback.progressCallback(window.findViewById<MyCircleProgress>(R.id.pro), tvTip)
        if (progressView.current == 100) {
            tvTip.text = "请稍后"
            progressView.postDelayed(Runnable { dialog.dismiss() }, 1000)
        }
        return dialog
    }

    /**秒杀 预约成功 弹窗
     * @author: merbng
     * @time: 2022/9/6 15:20
     * @description:
     */
    @JvmStatic
    fun showSeckillInternetSuccessDialog(act: Activity, startTime: String, advanceMinutes: String) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(false)
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.dialog_seckill_internet_success, null)
        val tvOk = view.findViewById<TextView>(R.id.tv_ok)
        view.findViewById<TextView>(R.id.tv_content).text = "1：${startTime} 开抢\n2：系统将在开抢前${advanceMinutes}分钟提醒\n3：已帮您提前加入购物车"
        tvOk.setOnClickListener {
            dialog.dismiss()
        }
        window.setContentView(view)
        window.setGravity(Gravity.CENTER)
    }

    interface IBottomShareWxExePosterCallBack {
        fun clickWxExe()
        fun clickPoster()
    }

    //底部弹窗，分享海报、小程序，
    fun showBottomSharePosterExe(act: Activity, callback: IBottomShareWxExePosterCallBack) {
        val dialog = AlertDialog.Builder(act, AlertDialog.THEME_HOLO_DARK).create()
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        val window = dialog.window
        window!!.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM)
        val lp = window.attributes
        lp.width = WindowManager.LayoutParams.MATCH_PARENT
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT
        window.decorView.setBackgroundColor(act.resources.getColor(R.color.transparent))
        window.attributes = lp
        val view = act.layoutInflater.inflate(R.layout.popup_share_poster_exe, null)
        view.findViewById<LinearLayout>(R.id.ll_share_wx).setOnClickListener {
            callback.clickWxExe()
            dialog.dismiss()
        }
        view.findViewById<LinearLayout>(R.id.ll_share_poster).setOnClickListener {
            callback.clickPoster()
            dialog.dismiss()
        }
        view.findViewById<RelativeLayout>(R.id.rl_cancel).setOnClickListener { dialog.dismiss() }
        view.findViewById<RelativeLayout>(R.id.rl_root).setOnClickListener { dialog.dismiss() }
        window.setContentView(view)
        window.setGravity(Gravity.BOTTOM)
    }
}